# 1导包
# 导入多张好自定义的包
import re  # 正则的包

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

from apps.users.models import User
from meiduo_mall.settings.dev import logger  # 日志文件的包


# 对函数进行封装
def generate_verify_email_url(user):
    host_url = settings.EMAIL_ACTIVE_URL
    data_dict = {
        'user_id': user.id,
        'email': user.email,
    }
    from utils.secret import SecretOauth
    dumps_params = SecretOauth().dumps(data_dict)
    verify_url = host_url + "?token=" + dumps_params
    return verify_url


# 校验用户名的函数
def get_user_by_account(account):
    try:
        # 3实现多张好校验手机号用户名名密码
        # 验证是否是手机号
        if re.match('^1[345789]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        # 将报错写入到日志文件
        logger.error('用户对象不存在')
        return None
    else:
        return user


# 2继承
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 现在在做后端，因为要去分时前端用户还是后端用户所以要做区分
        if request is None:
            # 后端调用时没有传request
            try:
                # 判断用户名是否正确还有就是是否是管理员
                user=User.objects.get(username=username,is_staff=True)
            except:
                # 不是返回空
                return None
            else:
                # 判断密码是否正确
                if user.check_password(password):
                    return user
                else:
                    # 不是返回空
                    return None
        else:
            # 是前端

            user = get_user_by_account(username)
            if user and user.check_password(password):
                return user
            else:
                return None
                # 4dev配置
